package org.example.review.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.common.pojo.entity.OperationLog;
import com.common.pojo.resp.ApprovalRecordRespDTO;
import org.example.review.dto.OperationLogDTO;
import org.example.review.mapper.OperationLogMapper;
import org.example.review.service.OperaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.stream.Collectors;

@Service
public class OperaServiceImpl implements OperaService {

    // 【正确】只注入 Mapper，不要定义任何成员变量来存储请求数据
    private final OperationLogMapper operationLogMapper;

    // 【正确】通过构造器注入
    public OperaServiceImpl(OperationLogMapper operationLogMapper) {
        this.operationLogMapper = operationLogMapper;
    }

    @Override
    public IPage<OperationLogDTO> getOperationLogs(Page<OperationLogDTO> page) {
        return operationLogMapper.selectAllOperationLogs(page);
    }

    @Override
    public boolean insertOperationLog(OperationLogDTO operationLogDTO) { // 参数名就用 operationLogDTO

        // 【正确】创建一个局部变量用于数据库操作
        OperationLog operationLogEntity = new OperationLog();

        // 【正确】使用方法参数（operationLogDTO）来给局部变量（operationLogEntity）赋值
        // 千万不要使用 this.operationLogDTO
        operationLogEntity.setApplyId(operationLogDTO.getApplyid());
        operationLogEntity.setRemark(operationLogDTO.getRemark());
        operationLogEntity.setIsChanged(operationLogDTO.getIschange());
        operationLogEntity.setDir(operationLogDTO.getDir());
        operationLogEntity.setStaff(operationLogDTO.getStaff());
        operationLogEntity.setStaffid(operationLogDTO.getStaffid());
        operationLogEntity.setDep(operationLogDTO.getDep());

        // 【正确】核心业务逻辑转换
        if ("approve".equalsIgnoreCase(operationLogDTO.getAction())) {
            operationLogEntity.setApprovalStatus(3);
        } else if ("reject".equalsIgnoreCase(operationLogDTO.getAction())) {
            operationLogEntity.setApprovalStatus(1);
        } else {
            System.err.println("未知的审批操作类型: " + operationLogDTO.getAction());
            return false;
        }

        operationLogEntity.setCreateTime(LocalDateTime.now()); // 如果没有自动填充

        // 【正确】调用 Mapper 插入局部变量
        int result = operationLogMapper.insert(operationLogEntity);

        // 【正确】根据返回结果判断成功与否
        return result > 0;
    }
    
    @Override
    public List<ApprovalRecordRespDTO> getApprovalRecordsByApplyId(Integer applyId) {
        // 根据applyId查询操作日志（applyId是Apply表的主键ID）
        LambdaQueryWrapper<OperationLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OperationLog::getApplyId, applyId)
               .orderByDesc(OperationLog::getCreateTime);  // 按时间倒序
        
        List<OperationLog> logs = operationLogMapper.selectList(wrapper);
        
        // 转换为ApprovalRecordRespDTO
        return logs.stream()
                .map(this::convertToApprovalRecordDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 将OperationLog转换为ApprovalRecordRespDTO
     */
    private ApprovalRecordRespDTO convertToApprovalRecordDTO(OperationLog log) {
        return ApprovalRecordRespDTO.builder()
                .id(log.getId())                      // 主键ID
                .applyId(log.getApplyId())            // 申请ID
                .approvalStatus(log.getApprovalStatus())  // 审批状态：1-驳回，3-通过
                .isChanged(log.getIsChanged())        // 是否更改：1-是，0-否
                .remark(log.getRemark())              // 审批意见
                .createTime(log.getCreateTime())      // 审批时间
                .dir(log.getDir())                    // 审批角色/职位
                .staff(log.getStaff())                // 审批人姓名
                .staffId(log.getStaffid())            // 审批人ID
                .dep(log.getDep())                    // 部门
                .adminId(null)                        // 管理员ID（如果OperationLog有此字段可映射）
                .build();
    }
}
